package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.User;

public class UserFilter implements Filter {
    User user1 = null;

    public void destroy() {
	user1 = null;
    }

    public void doFilter(ServletRequest request1, ServletResponse response1,
	    FilterChain chain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) request1;
	HttpServletResponse response = (HttpServletResponse) response1;
	// response.setCharacterEncoding("utf-8");
	user1 = (User) request.getSession().getAttribute("user");
	// String contexpath = request.getContextPath();
	String urlString = request.getRequestURI();
	if (!urlString.contains("/login.jsp")) {
	    if (user1 == null) {
		java.io.PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<script>");
		out.println("window.open ('../login.jsp','_top')");
		out.println("</script>");
		out.println("</html>");
		out.close();
		// response.sendRedirect("../login.jsp");
		return;
	    } else {
		String refererString = request.getHeader("referer");
		if (refererString != null) {		    
		    if (refererString.indexOf("/teacher/") > 0) {
			if (user1.getUsertype()<2) {
			    response.sendRedirect("../error.jsp?error=permissioin");
			    return;
			} else {
			    chain.doFilter(request1, response1);
			}
		    }else if (refererString.indexOf("/gradeheader/") > 0) {
			if (user1.getUsertype() <3) {
			    response.sendRedirect("../error.jsp?error=permissioin");
			    return;
			} else {
			    chain.doFilter(request1, response1);
			}
		    }
		    else if (refererString.indexOf("/admin/") > 0) {
			if (user1.getUsertype() <4) {
			    response.sendRedirect("../error.jsp?error=permissioin");
			    return;
			} else {
			    chain.doFilter(request1, response1);
			}
		    } else {
			chain.doFilter(request1, response1);
		    }
		}
	    }
	} else {
	    chain.doFilter(request1, response1);
	}

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
